package com.zrwl.poscloud.xo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrwl.poscloud.base.entity.MessageModel;
import com.zrwl.poscloud.base.entity.MessageSms;
import com.zrwl.poscloud.base.enums.EMessageModelType;
import com.zrwl.poscloud.base.enums.EStatus;
import com.zrwl.poscloud.base.superI.SuperServiceImpl;
import com.zrwl.poscloud.commons.utils.DateUtils;
import com.zrwl.poscloud.commons.utils.HttpRequestUtil;
import com.zrwl.poscloud.commons.utils.ResultUtil;
import com.zrwl.poscloud.xo.global.MessageConf;
import com.zrwl.poscloud.xo.global.SQLConf;
import com.zrwl.poscloud.xo.global.SysConf;
import com.zrwl.poscloud.xo.mapper.MessageSmsMapper;
import com.zrwl.poscloud.xo.service.MessageModelService;
import com.zrwl.poscloud.xo.service.MessageSmsService;
import com.zrwl.poscloud.xo.vo.AdminVO;
import com.zrwl.poscloud.xo.vo.MessageSmsVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 短信 服务实现类
 *
 * @author 刘思童 AutoGenerate
 * @date 2022-09-08
 */
@Service
public class MessageSmsServiceImpl extends SuperServiceImpl<MessageSmsMapper, MessageSms> implements MessageSmsService {

    @Autowired
    private MessageSmsService messageSmsService;
    @Resource
    private MessageSmsMapper messageSmsMapper;
    @Autowired
    private MessageModelService messageModelService;

    public static String sendTemplateMessage = "http://localhost:7603/sms/sendSMSMessage";

    @Override
    public IPage<MessageSmsVO> getPageList(MessageSmsVO messageSmsVO) {
        if (messageSmsVO.getKeyword().contains("#")) {
            String content = messageSmsVO.getKeyword();
            content = content.replace("#", "");
            messageSmsVO.setKeyword(content);
        }
        Page page = new Page<>();
        page.setCurrent(messageSmsVO.getCurrentPage());
        page.setSize(messageSmsVO.getPageSize());
        IPage<MessageSmsVO> pageList = messageSmsMapper.getPageList(page, messageSmsVO);
        List<MessageSmsVO> list = pageList.getRecords();
        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public List<MessageSms> getAllList(MessageSmsVO messageSmsVO) {
        QueryWrapper<MessageSms> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        queryWrapper.orderByAsc(SQLConf.CREATE_TIME);
        List<MessageSms> list = messageSmsService.list(queryWrapper);
        return list;
    }

    @Override
    public String add(MessageSmsVO messageSmsVO) {
        QueryWrapper<MessageSms> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("telephone", messageSmsVO.getMobile());
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        queryWrapper.orderByDesc(SQLConf.CREATE_TIME);
        queryWrapper.last("limit 1");
        MessageSms one = messageSmsService.getOne(queryWrapper);
        if (one != null) {
            int type = Integer.parseInt(EMessageModelType.SMS.getType()+ "0" + one.getModelType());
            switch (Objects.requireNonNull(EMessageModelType.getByValue(type))) {
                case SMS_VERIFICATION_CODE:
                    if (one.getSendTime() != null) {
                        if (DateUtils.addMinutes(one.getSendTime(), Integer.parseInt(one.getContent().split("##")[1])).after(new Date())) {
                            return ResultUtil.errorWithMessage("发送频繁,请稍后再发");
                        }
                    } else {
                        if (DateUtils.addMinutes(one.getCreateTime(), Integer.parseInt(one.getContent().split("##")[1])).after(new Date())) {
                            return ResultUtil.errorWithMessage("发送频繁,请稍后再发");
                        }
                    }
                    break;
            }
        }
        MessageSms entity = new MessageSms();
        BeanUtils.copyProperties(messageSmsVO, entity, SysConf.STATUS);
        entity.insert();
        messageSmsVO.setUid(entity.getUid());
        return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS);
    }

    @Override
    public String add(MessageSmsVO messageSmsVO, EMessageModelType eMessageModelType) {
        int type = eMessageModelType.getType();
        MessageModel templateMessage = messageModelService.getTemplateMessage(EMessageModelType.SMS, type % 10);
        messageSmsVO.setModelType(templateMessage.getType());
        return add(messageSmsVO);
    }

    @Override
    public String edit(MessageSmsVO messageSmsVO) {
        MessageSms entity = messageSmsService.getById(messageSmsVO.getUid());
        BeanUtils.copyProperties(messageSmsVO, entity);
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String delete(MessageSmsVO messageSmsVO) {
        MessageSms entity = messageSmsService.getById(messageSmsVO.getUid());
        entity.setStatus(EStatus.DISABLED);
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String sendMessage(MessageSmsVO messageSmsVO) {
        MessageSms entity = messageSmsService.getById(messageSmsVO.getUid());
        String sendStr = "telephone=" + entity.getMobile()
                + "&" + "type=" + messageSmsVO.getModelType()
                + "&" + "content=" + entity.getContent();
        Map<String, String> backStr = HttpRequestUtil.sendPost2(sendTemplateMessage, sendStr);
        if(HttpRequestUtil.checkState(backStr)){
            throw new RuntimeException("暂时无法连接，可能是由于系统出现故障，请联系管理员人工处理！");
        }
        if (backStr.get("result").contains("true")) {
            entity.setUpdateTime(new Date());
            entity.setStatus(2);
            //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
            entity.updateById();
        } else {
            entity.setUpdateTime(new Date());
            entity.setStatus(4);
            //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
            entity.updateById();
        }
        return backStr.get("data");
    }

    @Override
    public void sendMessage(List<AdminVO> adminVOS, MessageSmsVO messageSmsVO) {
        messageSmsVO.setBeginTime(DateUtils.getToDayStartTime());
        messageSmsVO.setEndTime(DateUtils.getToDayEndTime());
        for (AdminVO adminVO : adminVOS) {
            List<MessageSmsVO> messageSmsVOList = messageSmsMapper.getMessageSmsByCreateTime(messageSmsVO);
            if (messageSmsVOList.size() == 0) {
                messageSmsVO.setUid(null);
                messageSmsVO.setMobile(adminVO.getMobile());
                messageSmsService.add(messageSmsVO);
            }
        }
    }

    @Override
    public String addSend(MessageSmsVO messageSmsVO) {
        add(messageSmsVO);
        String sendAMessage = sendMessage(messageSmsVO);
        if (sendAMessage.contains("true")) {
            return ResultUtil.successWithMessage("发送成功");
        }
        return ResultUtil.errorWithMessage("发送失败,已存入短信消息中");
    }

    @Override
    public String resendMessage(MessageSmsVO messageSmsVO) {
        MessageSms entity = messageSmsService.getById(messageSmsVO.getUid());
        entity.setStatus(1);
        //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
        entity.updateById();
        return messageSmsService.sendMessage(messageSmsVO);
    }

    @Override
    public int getCurrentSMS(String telephone) {
        QueryWrapper<MessageSms> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("telephone", telephone);
        queryWrapper.eq(SQLConf.STATUS, 2);
        queryWrapper.ge("send_time", DateUtils.getToDayStartTime());
        queryWrapper.le("send_time", DateUtils.getToDayEndTime());
        queryWrapper.orderByDesc("update_time");
        return messageSmsService.count(queryWrapper);
    }

    @Override
    public MessageSms verificationCode(String userTelephone, String validCode) {
        QueryWrapper<MessageSms> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("telephone", userTelephone);
        queryWrapper.eq(SQLConf.STATUS, 2);
        queryWrapper.ge("create_time", DateUtils.getOneDayStartTime(new Date()));
        queryWrapper.le("create_time", DateUtils.getOneDayEndTime(new Date()));
        queryWrapper.orderByDesc("send_time");
        queryWrapper.last("limit 1");
        MessageSms messageSms = messageSmsService.getOne(queryWrapper);
        if (messageSms == null) {
            throw new RuntimeException("验证码已过期，请重新获取");
        }
        String code = messageSms.getContent().split("##")[0];
        if(!validCode.equals(code)){
            throw new RuntimeException("验证码错误");
        }else {
            int minute = Integer.parseInt(messageSms.getContent().split("##")[1]);
            DateUtils.formateDate(DateUtils.addMinutes(messageSms.getUpdateTime(), minute), "yyyy-MM-dd HH:mm:ss");
            if (DateUtils.addMinutes(messageSms.getSendTime(), minute).after(new Date())) {
                return messageSms;
            } else {
                throw new RuntimeException("验证码已过期，请重新获取");
            }
        }
    }

    @Override
    public List<MessageSmsVO> getUnsentSMSVerifyCode() {
        //获取未过期的短信验证码
        List<MessageSmsVO> unexpiredSMSVerifyCode = messageSmsMapper.getUnexpiredSMSVerifyCode();
        //获取未发送的短信验证码
        return messageSmsMapper.getUnsentSMSVerifyCode(unexpiredSMSVerifyCode);
    }
}
